package 位运算;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/*https://leetcode.cn/problems/single-number-iii/*/
public class 只出现一次的数字III {

    public static int[] singleNumber1(int[] nums) {
        int [] result =   new int[2];
        int c = 0;
        Map<Integer,Integer> hash = new HashMap<Integer,Integer>();
        for(int x:nums){

            Integer count = hash.get(x);
            count =  count == null ? 1 : ++count;
            hash.put(x,count);

        }
        for (Integer key : hash.keySet()){
            if(hash.get(key) == 1){
                result[c++] = key;
            }
        }
        return result;
    }
    public  static int[] singleNumber2(int[] nums) {
        int xorsum = 0;
        for (int num : nums) {
            xorsum ^= num;
        }
        // 防止溢出
        int lsb = (xorsum == Integer.MIN_VALUE ? xorsum : xorsum & (-xorsum));
        int type1 = 0, type2 = 0;
        for (int num : nums) {
            if ((num & lsb) != 0) {
                type1 ^= num;
            } else {
                type2 ^= num;
            }
        }
        return new int[]{type1, type2};
    }



    public static void main(String[] args) {
        int []nums= {1,2,1,3,2,5};
        int [] result = singleNumber2(nums);
        System.out.println(Arrays.toString(result));
    }
}

